﻿<%@ WebHandler Language="C#" Class="_2_防图片盗链" %>

using System;
using System.Web;

public class _2_防图片盗链 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
        //context.Response.ContentType = "text/plain";
        string fullPath = HttpContext.Current.Server.MapPath("图片1.jpg");

        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(fullPath))
        {
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
            {
                if (null == context.Request.UrlReferrer)
                {
                    g.Clear(System.Drawing.Color.White);
                    g.DrawString("禁止直接浏览图片",new System.Drawing.Font("宋体", 30), System.Drawing.Brushes.Red, 0, 0);
                }
                else if (context.Request.UrlReferrer.Host != "localhost")
                {
                    g.Clear(System.Drawing.Color.White);
                    g.DrawString("本图片仅供内部交流使用", new System.Drawing.Font("宋体", 30), System.Drawing.Brushes.Red, 0, 0);
                }
                
            }
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}